<?php
namespace app\admin\controller;
use think\facade\Db;
use app\admin\model\{Withdrawal as WithdrawModel,Distributor};
use app\admin\model\User;
use app\common\BaseController;
use hg\apidoc\annotation as Apidoc;
use think\Request;
use think\exception\ValidateException;
use app\common\support\PHPExcelService;

class Withdrawal extends BaseController{
    

    /**
     * @Apidoc\Title("列表")
     * @Apidoc\Url("Withdraw_index")
     * @Apidoc\Method("GET")
     * @Apidoc\Returned("data", type="array", desc="业务数据",replaceGlobal="true",
     *   @Apidoc\Returned("page",type="int",desc="页码"),
     *   @Apidoc\Returned("limit",type="int",desc="查询数量"),
     *   @Apidoc\Returned("data",type="array",desc="返回数据"),
     *   @Apidoc\Returned("total",type="array",desc="数据总量")
     * )
     */
    public function index(Request $request){
        $page  = (int)$request->param('page/d', 0);
        $limit  = (int)$request->param('limit/d', 10);
        $search = request()->param();
        $where = [];
            if(isset($search["name"]) && $search["name"]!="") $where[] = ["name","=",$search["name"]];
            if(isset($search["mobile"]) && $search["mobile"]!="") $where[] = ["mobile","=",$search["mobile"]];
            if(isset($search["status"]) && $search["status"]!="") $where[] = ["status","=",$search["status"]];

        $query  = WithdrawModel::with('disuser')->where($where);
        $total  = $query->count();
        $data   = $query->page($page,$limit)->order('id desc')->append(['status_text'])->select();
        return $this->success('', [
            'start' => $page,
            'limit' => $limit,
            'data'  => $data,
            'total' => $total,
        ]);
    }

    
        /**
     * @Apidoc\Title ("详情")
     * @Apidoc\Url("Withdraw_get")
     * @Apidoc\Method("GET")
     * @Apidoc\Param("id", type="int", require=true, desc="id")
     * @Apidoc\Returned("data", type="array", desc="业务数据",replaceGlobal="true",
     *   @Apidoc\Returned("data",type="string",desc="信息")
     * )
     */
    public function detail(int $id): \think\response\Json
    {
        try {
            $row  = WithdrawModel::where('id', $id)->find();
        } catch (DataNotFoundException | ModelNotFoundException | DbException $e) {
            return $this->error($e->getMessage());
        }

        return $this->success('', $row);
    }










    
        /**
     * @Apidoc\Title ("审核通过")
     * @Apidoc\Url("Withdraw_yes")
     * @Apidoc\Method("POST")
     * @Apidoc\Param("id", type="int", require=true, desc="id")
     */
    public function yes(): \think\response\Json
    {
        $id = \param_check('ids');
            $data = request()->post();
            try{
                $WithdrawalModel = WithdrawModel::find($id);
                if (!$WithdrawalModel) exception('数据不存在!');
                if($WithdrawalModel->status > 0) exception('订单状态异常');
                $service             = new \app\common\api\WeChat;
                $refund_order_sn     = 'TK'.$id.time(); //退款单号  自行生成
                $res = $service->dotransfer($WithdrawalModel->user->openid,$WithdrawalModel->amount,$refund_order_sn);
                if(!$res) exception('操作失败');
                $WithdrawalModel->payment_no = $res['payment_no'];
                $WithdrawalModel->payment_time = $res['payment_time'];
                $WithdrawalModel->status = 1;
                $WithdrawalModel->save();
                Db::commit();
            }catch(\Exception $e){
                Db::rollback();
                return $this->error($e->getMessage());  
            }
            return $this->success('操作成功');  
    }

    /**
     * 审核拒绝
     */
    public function no(): \think\response\Json
    {
        $id = \param_check('ids');
            $data = request()->post();
            try{
                $WithdrawalModel = WithdrawModel::find($id);
                if (!$WithdrawalModel) exception('数据不存在!');
                if($WithdrawalModel->status > 0) exception('订单状态异常');
                $res =  Distributor::income($WithdrawalModel->uid,$WithdrawalModel->amount,2);
                if(!$res) exception('操作失败');
                $WithdrawalModel->status = 2;
                $WithdrawalModel->save();
                Db::commit();
            }catch(\Exception $e){
                Db::rollback();
                return $this->error($e->getMessage());  
            }
            return $this->success('操作成功');  
         
    }

    //导出
     public function export_excell(){
        $search = request()->param();
        $where = [];
                    if(isset($search["name"]) && $search["name"]!="") $where[] = ["name","=",$search["name"]];
            if(isset($search["mobile"]) && $search["mobile"]!="") $where[] = ["mobile","=",$search["mobile"]];
            if(isset($search["level"]) && $search["level"]!="") $where[] = ["level","=",$search["level"]];
            if(isset($search["status"]) && $search["status"]!="") $where[] = ["status","=",$search["status"]];
            if(isset($search["balance"]) && $search["balance"]!="") $where[] = ["balance","=",$search["balance"]];

        $query  = WithdrawModel::where($where);
        big_array_to_csv($query,'data.csv',[]);
    }



        /**
     * 导入
     * @return void
     * @author Sam
     */
    public function import_excell(){
        if(empty($_FILES['file'])) json_response(0, '请选择文件');
        $list = big_csv_to_array($_FILES['file']['tmp_name']);
        try{
            $num = 0;
            if(count($list)){
                foreach($list as $k=>$v){
                    $data = [
                        'create_time'=>time(),
                        'update_time'=>time(),
                    ];
                $res =  WithdrawModel::create($data);
                if($res) $num++;
                }
            }
                return  $this->success('导入成功'.$num.'条数据');
            }catch(\Exception $e){
                return $this->error($e->getMessage());
            }
        }
}